import { defineEventHandler, getQuery, readBody } from 'h3';

import { usePageResponseSuccess, useResponseError } from '../utils/response';

// 生成历史维保记录数据的辅助函数
function generateAuditRecordData() {
  const auditRecords = [];
  const baseRecordId = 60_001;

  // 模拟车辆和司机数据（符合7位车牌格式）
  const vehicles = [
    { vehicleId: 30_001, licensePlate: '京A12345' },
    { vehicleId: 30_002, licensePlate: '京B56789' },
    { vehicleId: 30_003, licensePlate: '京C90123' },
    { vehicleId: 30_004, licensePlate: '京D34567' },
    { vehicleId: 30_005, licensePlate: '京E78901' },
    { vehicleId: 30_006, licensePlate: '京F12345' },
    { vehicleId: 30_007, licensePlate: '京G56789' },
    { vehicleId: 30_008, licensePlate: '京H90123' },
    { vehicleId: 30_009, licensePlate: '京J34567' },
    { vehicleId: 30_010, licensePlate: '京K78901' },
  ];

  const drivers = [
    { driverId: 10_001, driverName: '张三' },
    { driverId: 10_002, driverName: '李四' },
    { driverId: 10_003, driverName: '王五' },
    { driverId: 10_004, driverName: '赵六' },
    { driverId: 10_005, driverName: '孙七' },
    { driverId: 10_006, driverName: '周八' },
    { driverId: 10_007, driverName: '吴九' },
    { driverId: 10_008, driverName: '郑一' },
    { driverId: 10_009, driverName: '王二' },
    { driverId: 10_010, driverName: '陈三' },
  ];

  // 审批状态
  const approvalStatuses = ['已批准', '已驳回', '待审批'];

  // 故障描述模板
  const descriptions = [
    '发动机异响，需要检查',
    '常规保养，更换机油',
    '刹车系统检查',
    '轮胎更换',
    '空调系统维修',
    '变速箱油更换',
    '电瓶更换',
    '四轮定位',
    '雨刷更换',
    '全车检查',
    '机油滤清器更换',
    '火花塞更换',
    '刹车片更换',
    '轮胎动平衡',
    '空调滤清器更换',
    '燃油系统清洗',
    '节气门清洗',
    '冷却系统检查',
    '电瓶检测',
    '灯光系统检查',
  ];

  // 生成30条历史记录
  for (let i = 0; i < 30; i++) {
    const vehicle = vehicles[i % vehicles.length];
    const driver = drivers[i % drivers.length];
    const requestType = i % 2 === 0 ? '维修' : '保养';
    const description = descriptions[i % descriptions.length];
    const approvalStatus = approvalStatuses[Math.floor(Math.random() * 3)];

    // 生成随机的申请时间（近6个月）
    const year = 2024;
    const month = Math.floor(Math.random() * 6) + 1;
    const day = Math.floor(Math.random() * 28) + 1;
    const hour = Math.floor(Math.random() * 24);
    const minute = Math.floor(Math.random() * 60);
    const applyTime = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')} ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;

    // 生成随机的审批时间（申请时间后1-7天）
    const approvalDay = day + Math.floor(Math.random() * 7) + 1;
    const approvalHour = Math.floor(Math.random() * 24);
    const approvalMinute = Math.floor(Math.random() * 60);
    const approvalTime = `${year}-${month.toString().padStart(2, '0')}-${approvalDay.toString().padStart(2, '0')} ${approvalHour.toString().padStart(2, '0')}:${approvalMinute.toString().padStart(2, '0')}`;

    // 生成随机的维保费用（200-3000元）
    const cost = Math.round(Math.random() * 2800 + 200);

    // 生成图片URL（至少1条有图，1条无图）
    const images = [];
    if (i % 3 === 0) {
      images.push(`/mock/images/car${i + 1}.jpg`);
    }

    auditRecords.push({
      record_id: baseRecordId + i,
      vehicle_id: vehicle.vehicleId,
      license_plate: vehicle.licensePlate,
      driver_id: driver.driverId,
      driver_name: driver.driverName,
      request_type: requestType,
      description,
      approval_status: approvalStatus,
      cost,
      apply_time: applyTime,
      approval_time: approvalTime,
      images,
    });
  }

  return auditRecords;
}

// 历史维保记录数据模拟
const auditRecords = generateAuditRecordData();

// 获取历史维保记录
export const getAuditRecordsHandler = defineEventHandler(async (event) => {
  try {
    const query = getQuery(event);
    const page = Number.parseInt(query.page as string) || 1;
    const pageSize = Number.parseInt(query.pageSize as string) || 20;
    const licensePlate = query.licensePlate as string;
    const driverName = query.driverName as string;
    const requestType = query.requestType as string;
    const approvalStatus = query.approvalStatus as string;

    // 筛选数据
    let filteredData = auditRecords;

    if (licensePlate) {
      filteredData = filteredData.filter((item) =>
        item.license_plate.includes(licensePlate),
      );
    }

    if (driverName) {
      filteredData = filteredData.filter((item) =>
        item.driver_name.includes(driverName),
      );
    }

    if (requestType) {
      filteredData = filteredData.filter(
        (item) => item.request_type === requestType,
      );
    }

    if (approvalStatus) {
      filteredData = filteredData.filter(
        (item) => item.approval_status === approvalStatus,
      );
    }

    // 分页处理
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedData = filteredData.slice(startIndex, endIndex);

    return usePageResponseSuccess(page, pageSize, paginatedData, {
      message: '获取成功',
    });
  } catch {
    return useResponseError('获取失败');
  }
});

// 导出历史维保记录
export const exportAuditRecordsHandler = defineEventHandler(async (event) => {
  try {
    const body = await readBody(event);
    const licensePlate = body.licensePlate;
    const driverName = body.driverName;
    const requestType = body.requestType;
    const approvalStatus = body.approvalStatus;

    // 筛选数据用于导出
    let filteredData = auditRecords;

    if (licensePlate) {
      filteredData = filteredData.filter((item) =>
        item.license_plate.includes(licensePlate),
      );
    }

    if (driverName) {
      filteredData = filteredData.filter((item) =>
        item.driver_name.includes(driverName),
      );
    }

    if (requestType) {
      filteredData = filteredData.filter(
        (item) => item.request_type === requestType,
      );
    }

    if (approvalStatus) {
      filteredData = filteredData.filter(
        (item) => item.approval_status === approvalStatus,
      );
    }

    // 模拟导出延迟
    await new Promise((resolve) => setTimeout(resolve, 1000));

    return useResponseSuccess({
      downloadUrl: '/api/maintenance/auditRecord/export/download',
      fileName: `历史维保记录_${new Date().toISOString().slice(0, 10)}.xlsx`,
    });
  } catch {
    return useResponseError('导出失败');
  }
});
